#include "encoding_manager.h"
#include "config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static PT_EncodingOpr g_ptEncodingOprHead;

int RegisterEncodingOpr(PT_EncodingOpr ptEncodingOpr)
{
    PT_EncodingOpr ptTmp;
    if (!g_ptEncodingOprHead)
    {
        g_ptEncodingOprHead = ptEncodingOpr;
        ptEncodingOpr->ptNext = NULL;
    }
    else
    {
        ptTmp = g_ptEncodingOprHead;
        while (ptTmp->ptNext)
        {
            ptTmp = ptTmp->ptNext;
        }
        ptTmp->ptNext = ptEncodingOpr;
        ptEncodingOpr->ptNext = NULL;
    }
    return 0;
}

int EncodingInit(void)
{
    int ret;

    ret = AsciiEncodingInit();
    if (ret)
    {
        DBG_PRINTF("AsciiEncodingInit error!\n");
        return -1;
    }

    ret = Utf16leEncodingInit();
    if (ret)
    {
        DBG_PRINTF("Utf16leEncodingInit error!\n");
        return -1;
    }

    ret = Utf16beEncodingInit();
    if (ret)
    {
        DBG_PRINTF("Utf16beEncodingInit error!\n");
        return -1;
    }

    ret = Utf8EncodingInit();
    if (ret)
    {
        DBG_PRINTF("Utf8EncodingInit error!\n");
        return -1;
    }

    return 0;
}

void ShowEncodingOpr(void)
{
    int i = 0;
    PT_EncodingOpr ptTmp = g_ptEncodingOprHead;

    while (ptTmp)
    {
        printf("%02d %s\n", i++, ptTmp->name);
        ptTmp = ptTmp->ptNext;
    }
}
PT_EncodingOpr SelectEncodingOprForFile(unsigned char *pucFileBufHead)
{
    PT_EncodingOpr tmp = g_ptEncodingOprHead;
    while (tmp)
    {
        if (tmp->isSupport(pucFileBufHead) == 0)
        {
            return tmp;
        }
        tmp = tmp->ptNext;
    }
    return NULL;
}

int AddFontOprForEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
    if (!ptEncodingOpr || !ptFontOpr)
    {
        DBG_PRINTF("AddFontOprForEncoding error");
        return -1;
    }
    PT_FontOpr tmp = malloc(sizeof(T_FontOpr));
    memcpy(tmp, ptFontOpr, sizeof(T_FontOpr));
    tmp->ptNext = ptEncodingOpr->ptFontOprSupportedHead;
    ptEncodingOpr->ptFontOprSupportedHead = tmp;
    return 0;
}
int DelFontOprFrmEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
	PT_FontOpr ptTmp;
	PT_FontOpr ptPre;
		
	if (!ptEncodingOpr || !ptFontOpr)
	{
		return -1;
	}
	else
	{
		ptTmp = ptEncodingOpr->ptFontOprSupportedHead;
		if (strcmp(ptTmp->name, ptFontOpr->name) == 0)
		{
			ptEncodingOpr->ptFontOprSupportedHead = ptTmp->ptNext;
			free(ptTmp);
			return 0;
		}

		ptPre = ptEncodingOpr->ptFontOprSupportedHead;
		ptTmp = ptPre->ptNext;
		while (ptTmp)
		{
			if (strcmp(ptTmp->name, ptFontOpr->name) == 0)
			{
				ptPre->ptNext = ptTmp->ptNext;
				free(ptTmp);
				return 0;
			}
			else
			{
				ptPre = ptTmp;
				ptTmp = ptTmp->ptNext;
			}
		}

		return -1;
	}
}